package com.song.webutil;

import com.song.damain.Forum;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.cookie.Cookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by wangsong on 2015/8/27.
 *
 */
public class TieBaSign {

    private HttpUtils httpUtils = null;


    public TieBaSign() {
        httpUtils = new HttpUtils();
    }

    public HttpUtils getHttpUtile() {
        return httpUtils;
    }


    Logger logger = LogManager.getLogger(TieBaSign.class);

    public boolean getBauDuID() {

        logger.error("====== 步骤1：获得BAIDUID的Cookie ======");

        String url = "http://www.baidu.com/";
        HttpResponse httpResponse = httpUtils.getUrlResponse(url);
        List<Cookie> curCookieList = httpUtils.getCurCookieList();
        httpUtils.dbgPrintCookies(curCookieList, url);
        for (Cookie ck : curCookieList) {
            String cookieName = ck.getName();
            if (cookieName.equals("BAIDUID")) {
                logger.error("正确：已找到cookie BAIDUID");
                return true;
            } else {
                logger.error("错误：没有找到cookie BAIDUID");

            }
        }
        return false;
    }


    public String getStrTokenValue() {

        logger.error("====== 步骤2：获得百度的token ======");

        String token = "";
        String getapiUrl = "https://passport.baidu.com/v2/api/?getapi&class=login&tpl=mn&tangram=true";
        String getApiRespHtml = httpUtils.getUrlRespHtml(getapiUrl);
        Pattern tokenValP = Pattern.compile("login_token='(.*?)';");
        Matcher tokenValMatcher = tokenValP.matcher(getApiRespHtml);
        boolean foundTokenValue = tokenValMatcher.find();
        if (foundTokenValue) {
            token = tokenValMatcher.group(1); //3cf421493884e0fe9080593d05f4744f

            logger.error("正确：找到 bdPass.api.params.login_token="+token);

        } else {

            logger.error("错误：没找到bdPass.api.params.login_token !");
        }
        return token;
    }


    public boolean loginIn(String username, String password, String token) {


        logger.error("======步骤3：登陆百度并检验返回的Cookie ======");

        String staticPageUrl = "http://www.baidu.com/cache/user/html/jump.html";

        List<NameValuePair> postDict = new ArrayList<NameValuePair>();
        postDict.add(new BasicNameValuePair("charset", "utf-8"));
        postDict.add(new BasicNameValuePair("token", token));
        postDict.add(new BasicNameValuePair("isPhone", "false"));
        postDict.add(new BasicNameValuePair("index", "0"));
        postDict.add(new BasicNameValuePair("staticpage", staticPageUrl));
        postDict.add(new BasicNameValuePair("loginType", "1"));
        postDict.add(new BasicNameValuePair("tpl", "mn"));
        postDict.add(new BasicNameValuePair("callback", "parent.bdPass.api.login._postCallback"));
        postDict.add(new BasicNameValuePair("username", username));
        postDict.add(new BasicNameValuePair("password", password));
        postDict.add(new BasicNameValuePair("verifycode", ""));
        postDict.add(new BasicNameValuePair("mem_pass", "on"));

        String baiduMainLoginUrl = "https://passport.baidu.com/v2/api/?login";
        String loginBaiduRespHtml = httpUtils.getUrlRespHtml(baiduMainLoginUrl, null, postDict);

        HashMap<Object, Boolean> cookieNameDict = new HashMap<Object, Boolean>();
        cookieNameDict.put("BDUSS", false);
        cookieNameDict.put("PTOKEN", false);
        cookieNameDict.put("STOKEN", false);
        List<Cookie> curCookieList = httpUtils.getCurCookieList();
        for (Object objCookieName : cookieNameDict.keySet().toArray()) {
            String strCookieName = objCookieName.toString();
            for (Cookie ck : curCookieList) {
                if (strCookieName.equalsIgnoreCase(ck.getName())) {
                    cookieNameDict.put(strCookieName, true);
                }
            }
        }
        boolean bAllCookiesFound = true;
        for (Object objFoundCurCookie : cookieNameDict.values()) {
            bAllCookiesFound = bAllCookiesFound && Boolean.parseBoolean(objFoundCurCookie.toString());
        }
        boolean bLoginBaiduOk = bAllCookiesFound;
        if (bLoginBaiduOk) {
            logger.error("成功模拟登陆百度首页");
            logger.error(loginBaiduRespHtml);
            return true;
        } else {
            logger.error("模拟登陆百度首页 失败！");
            logger.error(loginBaiduRespHtml);
            return false;
        }
    }


    public List<Forum> getFavouriteForums() {
        List<Forum> forumList = new ArrayList<Forum>();

        logger.error("====== 步骤4：获得全部关注的贴吧 ======");

        String tiebamain = "http://tieba.baidu.com/";
        String htmltext = httpUtils.getUrlRespHtml(tiebamain);

        String reg = "(\\{\"forums\":\\[\\{.*?),\"directory\":\\{";
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(htmltext);
        String jsontext = "";

        boolean flag;
        flag = m.find();

        if (flag) {
            jsontext = m.group(1) + "}";
            JSONObject jsonObject = JSONObject.fromObject(jsontext);
            JSONArray jsonArray = jsonObject.getJSONArray("forums");

            for (int i = 0; i < jsonArray.size(); i++) {
                forumList.add(new Forum(jsonArray.getJSONObject(i).getString("user_id"),
                        jsonArray.getJSONObject(i).getString("forum_id"),
                        jsonArray.getJSONObject(i).getString("forum_name"),
                        jsonArray.getJSONObject(i).getLong("in_time"),
                        jsonArray.getJSONObject(i).getInt("level_id"),
                        jsonArray.getJSONObject(i).getInt("cur_score"),
                        jsonArray.getJSONObject(i).getInt("score_left"),
                        jsonArray.getJSONObject(i).getString("level_name"),
                        jsonArray.getJSONObject(i).getInt("is_sign")));
            }

            logger.error("成功获得全部关注的贴吧信息");
        } else {
            logger.error("获取关注贴吧信息失败");
        }
        return forumList;
    }


    public List<String> getNoSignUrl(List<Forum> forums,
                                     UpdateGetNoSignProgressCallback updateGetNoSignProgressCallback) {

        logger.error("====== 步骤5：得到全部没有签到的贴吧的签到的URL地址 ======");

        List<Forum> nosignForus = new ArrayList<Forum>();

        for (Forum f : forums) {
            if (f.getIs_sign() == 0) {
                nosignForus.add(f);
            }
        }
        //http://wapp.baidu.com/m?kw=%E6%9D%8E%E6%AF%85
        List<String> nosignurls = new ArrayList<String>();
        int count = nosignForus.size();
        for (int i = 0; i < count; i++) {
            String nosignurl = "";
            String nosigntext = null;
            try {
                nosigntext = httpUtils.getUrlRespHtml
                        ("http://wapp.baidu.com/m?kw=" +
                                URLEncoder.encode(nosignForus.get(i).getForum_name(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String nosignreg = "<a href=\"(/mo/q.*?)\">签到</a>";
            Pattern p1 = Pattern.compile(nosignreg);
            Matcher m1 = p1.matcher(nosigntext);
            while (m1.find()) {
                nosignurl = "http://tieba.baidu.com" + m1.group(1);
                nosignurls.add(nosignurl.replaceAll("&amp;", "&"));
            }
            logger.error("签到地址：" + nosignurl);

            if(null == updateGetNoSignProgressCallback || updateGetNoSignProgressCallback.equals(null)){
                System.out.println("**************updateGetNoSignProgressCallback为空*********");
            }else {
                updateGetNoSignProgressCallback.updateProgress(count, i + 1, forums.get(i).getForum_name());
            }



        }
        return nosignurls;
    }

    public List<String> signByURL(String singurl) {
        logger.error("================= 开始签到 ===================");
        List<String> signresult = new ArrayList<String>();
        String htmltext = httpUtils.getUrlRespHtml(singurl);
        String reg = "<div><a name=\"top\"></a><span class=\"light\">(.*?)<span class=\"light\">(.*?)</span><br/>";
        //String reg = "签到";
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(htmltext);
        logger.error("签到" + singurl + ":");
        if (m.find()) {
            //1.你签得太快了，先看看贴子再来签吧：）
            //2.亲，你之前已经签过了
            //3.签到成功，经验值上升  5
            signresult.add(m.group(1));
            signresult.add(m.group(2));
            logger.error("！！成功！！" + m.group(1) + m.group(2));
        } else {
            logger.error("！！失败！！");
        }
        return signresult;
    }


    public interface UpdateGetNoSignProgressCallback {
        public void updateProgress(int count, int index, String name);
    }


}
